<template>
  <div class="m-page">
    <m-header title="生产监控看板"></m-header>
    <div class="m-body">
      <dv-border-box-8 :reverse="true" :dur="20" class="first-floor">
        <m-row :gutter="20">
          <m-col :span="24 / totals.length" v-for="t in totals" :key="t.color">
            <m-num-board align="horizontal" :color="t.color" :title="t.title" :number="t.number"
              :isFormat="t.isFormat" />
          </m-col>
        </m-row>
      </dv-border-box-8>

      <m-row :gutter="20" class="second-floor">
        <m-col :span="12">
          <m-box title="工序生产达成率（当月）">
            <m-scroll-board :row-num="7" :loading="stationLoading" :cols="stationCols" :datas="stationData" />
          </m-box>
        </m-col>
        <m-col :span="12">
          <m-box title="工单进度监控（未完工）">
            <m-scroll-board :row-num="7" :loading="orderLoading" :cols="orderCols" :datas="orderData" />
          </m-box>
        </m-col>
      </m-row>
      <m-row :gutter="20" class="third-floor">
        <m-col :span="12">
          <m-box title="品质监控（当月）" class="quality">
            <div class="quality-box">
              <m-ring-chart
                title="<div class='m-ring-chart__title'><i class='m-ring-chart__icon'></i>良品率 <i class='m-ring-chart__icon'></i>不良品率</div>"
                :show-origin-value="false" :loading="qualityLoading" :cols="qualityRateCols" :datas="qualityRateData" />
              <div class="slice"></div>
              <m-ring-chart
                title="<div class='m-ring-chart__title'><i class='m-ring-chart__icon'></i>良品数 <i class='m-ring-chart__icon'></i>不良品数</div>"
                :loading="qualityLoading" :cols="qualityCols" :datas="qualityData" />
            </div>
          </m-box>
        </m-col>
        <m-col :span="12">
          <m-box title="设备监控（当日）">
            <m-scroll-board :row-num="7" :loading="equipmentLoading" :cols="equipmentCols" :datas="equipmentData" />
          </m-box>
        </m-col>
      </m-row>
    </div>
  </div>
</template>

<script setup>
// 其他方法
import http from '@/utils/request'
import { randomColor } from '@/utils/tools'
// vue提供的api
import { ref, onBeforeMount } from 'vue'

const totals = ref([
  { color: '#FFF8DC', title: '当月产量', code: 'PPR', number: 0 },
  { color: '#7FFF00', title: '当日产量', code: 'MI', number: 0 },
  { color: '#00FFFF', title: '总达成率', code: 'MO', number: 0 },
  { color: '#00BFFF', title: '完工及时率', code: 'PPR', number: 0 }
  // { color: '#BA55D3', title: '杂项入库数', code: 'OI', number: Math.ceil(Math.random() * 1000000) },
  // { color: '#FF7F50', title: '杂项出库数', code: 'OO', number: Math.ceil(Math.random() * 1000000) }
])

// 随机生成颜色值
function statusFormat(value) {
  const RUNNING_STATUS = {
    0: "待机",
    1: "运行",
    2: "报警"
  }
  const RUNNING_COLOR = {
    0: "yellow",
    1: "green",
    2: "red"
  }
  return `<span style="color: ${RUNNING_COLOR[value]}">${RUNNING_STATUS[value]}</span>`
}

// 工序生产达成率（当月）
const stationCols = ref([
  { width: 40, title: '序号', type: 'seq', align: 'center' },
  { width: 200, title: '工序', property: 'STATION_NAME' },
  { width: 160, title: '总排产数量', property: 'PLAN_QTY' },
  { width: 160, title: '总完工数量', property: 'COMPLETED_QTY' },
  { width: 160, title: '未完成数量', property: 'UNFINISHED_QTY' },
  { width: 160, title: '达成率', property: 'COMPLETED_RATE', formatter: ({ value }) => formatPercentage(value) }
])
const stationLoading = ref(false)
const stationData = ref([])

// 工单进度监控（未完工）
const orderCols = ref([
  { width: 40, title: '序号', type: 'seq', align: 'center' },
  { width: 130, title: '工单号', property: 'MO_CODE' },
  { width: 150, title: '产品编码', property: 'MITEM_CODE' },
  { width: 180, title: '产品名称', property: 'MITEM_NAME' },
  { width: 180, title: '规格型号', property: 'SPECIFICATION' },
  { width: 180, title: '工序', property: 'STATION_NAME' },
  { width: 120, title: '排产数', property: 'PLAN_QTY' },
  { width: 100, title: '完工数', property: 'COMPLETED_QTY' },
  // {
  //   width: 120,
  //   title: '检验状态',
  //   property: '检验状态',
  //   formatter: ({ value }) => statusFormat(value)
  // }
])
const orderLoading = ref(false)
const orderData = ref([])

// 设备监控（当日）
const equipmentCols = ref([
  { width: 40, title: '序号', type: 'seq', align: 'center' },
  { width: 260, title: '设备名称', property: 'EQUIPMENT_NAME' },
  { width: 180, title: '运行时长(分钟)', property: 'RUNNING_DURATION' },
  {
    width: 180,
    title: '运行状态',
    property: 'RUNNING_STATUS',
    formatter: ({ value }) => statusFormat(value)
  },
  { width: 180, title: '稼动率', property: 'OPERATING_RATE', formatter: ({ value }) => formatPercentage(value) }
])
const equipmentLoading = ref(false)
const equipmentData = ref([])

// 品质监控（当月）
const qualityRateCols = ref([
  { name: '良品率', property: '良品率' },
  { name: '不良品率', property: '不良品率' }
])
const qualityRateData = ref({ 良品率: 0, 不良品率: 0 })

const qualityCols = ref([
  { name: '良品数', property: '良品数' },
  { name: '不良品数', property: '不良品数' }
])
const qualityLoading = ref(false)
const qualityData = ref({ 良品数: 0, 不良品数: 0 })

const formatPercentage = (value) => {
  return Number(value).toFixed(4) + '%';
}

// 模拟接口请求，延迟1秒返回数据
function getData(len, cols) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = Array.from({ length: len }).map((r, i) => {
        const idx = i + 1
        const newRow = cols.reduce((res, _) => {
          if (_.type !== 'seq') {
            res[_.property] = _.title + idx
          }
          return res
        }, {})
        return newRow
      })
      resolve(res)
    }, 1000)
  })
}

// 获取工单统计(头)
const getMOStatisticsReport = async () => {
  try {
    const data = await http.get('/v1/kanban/getMOStatisticsReport')
    let { monthlyOutput, onDutyOutput, completionPercentage, timelyCompletionRate } = data;
    completionPercentage = formatPercentage(completionPercentage)
    timelyCompletionRate = formatPercentage(timelyCompletionRate)
    totals.value = [
      { color: '#FFF8DC', title: '当月产量', code: 'PPR', number: monthlyOutput },
      { color: '#7FFF00', title: '当日产量', code: 'MI', number: onDutyOutput },
      { color: '#00FFFF', title: '总达成率', code: 'MO', number: completionPercentage, isFormat: false },
      { color: '#00BFFF', title: '完工及时率', code: 'PPR', number: timelyCompletionRate, isFormat: false }
    ]
  } catch (error) {
    console.log(error);
  }
}

// 获取 工序生产达成率（当月） 数据
const getScheduleProductionAchievementRateReport = async () => {
  try {
    stationLoading.value = true
    const params = {
      pageindex: 1,
      pagesize: 100
    }
    const data = await http.get('v1/kanban/getScheduleProductionAchievementRateReport', params)
    stationData.value = data.data
    stationLoading.value = false;
  } catch (error) {
    console.log(error);
    stationLoading.value = false;
  }
}

// 获取 工单进度监控（未完工） 数据
const getMOMonitoringReport = async () => {
  try {
    orderLoading.value = true
    const params = {
      pageindex: 1,
      pagesize: 100
    }
    const data = await http.get('v1/kanban/getMOMonitoringReport', params)
    orderData.value = data.data
    orderLoading.value = false;
  } catch (error) {
    console.log(error);
    orderLoading.value = false;
  }
}


// 获取 设备监控（当日） 数据
const geteQuipmentMonitoringReport = async () => {
  try {
    equipmentLoading.value = true
    const params = {
      pageindex: 1,
      pagesize: 100
    }
    const data = await http.get('v1/kanban/GeteQuipmentMonitoringReport', params)
    equipmentData.value = data.data
    equipmentLoading.value = false;
  } catch (error) {
    console.log(error);
    equipmentLoading.value = false;
  }
}

// 获取品质监控
const getQualityMonitoringReport = async () => {
  try {
    qualityLoading.value = true
    const params = {
      pageindex: 1,
      pagesize: 100
    }
    const data = await http.get('v1/kanban/GetQualityMonitoringReport', params)
    const { totalNgQty, totalGpQty, ngRate, gpRate } = data;
    qualityRateData.value = ref({ 良品率: gpRate, 不良品率: ngRate })
    if(ngRate == 0){
      qualityRateCols.value.splice(1,1)
    }
    qualityData.value = ref({ 良品数: totalGpQty, 不良品数: totalNgQty })
    if(totalNgQty == 0){
      qualityCols.value.splice(1,1)
    }
    qualityLoading.value = false;
  } catch (error) {
    console.log(error);
    qualityLoading.value = false;
  }
}

function init() {
  // 获取工单统计(头)
  getMOStatisticsReport();

  // 获取 工序生产达成率（当月） 数据
  getScheduleProductionAchievementRateReport();

  // 获取 工单进度监控（未完工） 数据
  getMOMonitoringReport();

  // 获取 设备监控（当日） 数据
  geteQuipmentMonitoringReport();

  // 获取品质监控
  getQualityMonitoringReport();
}

let timeId = null;
onBeforeMount(async () => {
  init();
  timeId = setInterval(() => {
    init()
  }, 1000 * 60 * 10)
})

onBeforeUnmount(async () => {
  clearInterval(timeId)
})
</script>
<style lang="less" scoped>
.m-page {
  .m-body {
    ::v-deep(.first-floor) {
      height: 100px;
      width: calc(100% - 30px);
      margin-left: 15px;

      .border-box-content {
        position: relative;

        >.m-row {
          margin-bottom: 0;
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }

    >.m-row {
      margin-bottom: 0;

      &.second-floor,
      &.third-floor {
        height: calc((100% - 100px) / 2);

        .m-col {
          height: 100%;

          ::v-deep(.m-box.quality) {
            .m-box__body {
              .dv-border-box-7 {
                .border-box-content {
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  position: relative;

                  .quality-box {
                    display: flex;

                    .m-ring-chart {
                      .title {
                        .m-ring-chart__title {
                          display: flex;
                          align-items: center;

                          .m-ring-chart__icon {
                            display: inline-block;
                            width: 0.8em;
                            height: 0.8em;
                            margin-right: 5px;
                            background: rgb(0, 191, 255);

                            &:nth-child(2) {
                              background: rgb(255, 79, 71);
                              margin-left: 10px;
                            }
                          }
                        }
                      }
                    }

                    .slice {
                      width: 140px;
                      height: 100%;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
